import React, { useState, useRef } from 'react';
import {
    Tabs,
    Dropdown,
    Button,
    Space,
    Tooltip,
    Typography,
    theme
} from 'antd';
import {
    CloseOutlined,
    MoreOutlined,
    ReloadOutlined,
    CloseCircleOutlined,
    MinusCircleOutlined,
    DashboardOutlined,
    EnvironmentOutlined,
    SettingOutlined,
    DatabaseOutlined,
    BulbOutlined,
    UserOutlined,
} from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import useTabStore from '../../stores/tabStore';
import { useNavigate, useLocation } from 'react-router-dom';
import { useThemeConfig } from '../../contexts/ThemeConfigContext';
import { useNavigation } from '../../contexts/NavigationContext';
import './TabBar.css';

const { Text } = Typography;

const TabBar = () => {
    const { t } = useTranslation();
    const navigate = useNavigate();
    const location = useLocation();
    const { token } = theme.useToken();
    const { isDark } = useThemeConfig();
    const { onNavigate } = useNavigation();

    // 翻译标签页标题
    const getTabTitle = (tab) => {
        // 如果是国际化 key（以 'menu.' 开头），则翻译
        if (typeof tab.title === 'string' && tab.title.startsWith('menu.')) {
            return t(tab.title);
        }
        // 否则直接返回标题
        return tab.title;
    };

    // 图标映射函数
    const getIcon = (iconName) => {
        const iconMap = {
            'DashboardOutlined': <DashboardOutlined />,
            'EnvironmentOutlined': <EnvironmentOutlined />,
            'SettingOutlined': <SettingOutlined />,
            'DatabaseOutlined': <DatabaseOutlined />,
            'BulbOutlined': <BulbOutlined />,
            'UserOutlined': <UserOutlined />,
        };
        return iconMap[iconName] || <DashboardOutlined />;
    };

    const {
        tabs,
        activeTab,
        addTab,
        closeTab,
        closeOtherTabs,
        closeAllTabs,
        switchTab,
        reorderTabs,
        resetTabs,
        debugTabs
    } = useTabStore();

    const [dragIndex, setDragIndex] = useState(null);
    const [dragOverIndex, setDragOverIndex] = useState(null);
    const [isDragging, setIsDragging] = useState(false);
    const tabBarRef = useRef(null);

    // 开发环境下暴露调试方法到全局
    React.useEffect(() => {
        if (process.env.NODE_ENV === 'development') {
            window.__debugTabs = debugTabs;
            window.__resetTabs = resetTabs;
            console.log('TabBar 调试方法已加载：');
            console.log('- window.__debugTabs() - 查看当前标签页状态');
            console.log('- window.__resetTabs() - 重置所有标签页');
        }
    }, [debugTabs, resetTabs]);

    // 处理标签页点击
    const handleTabClick = (tabKey) => {
        const targetPath = switchTab(tabKey);
        if (targetPath && targetPath !== location.pathname) {
            // 使用带动画的导航
            onNavigate({ key: targetPath });
        }
    };

    // 处理标签页关闭
    const handleTabClose = (e, tabKey) => {
        e.stopPropagation();
        console.log(`尝试关闭标签页: ${tabKey}`);

        const newPath = closeTab(tabKey);
        console.log(`关闭后的新路径: ${newPath}`);

        if (newPath && newPath !== location.pathname) {
            // 使用带动画的导航
            onNavigate({ key: newPath });
        }
    };

    // 右键菜单项
    const getContextMenu = (tab) => ({
        items: [
            {
                key: 'reload',
                label: '刷新页面',
                icon: <ReloadOutlined />,
                onClick: () => window.location.reload(),
            },
            {
                type: 'divider',
            },
            {
                key: 'close',
                label: '关闭标签页',
                icon: <CloseOutlined />,
                disabled: !tab.closable,
                onClick: () => {
                    const newPath = closeTab(tab.key);
                    if (newPath && newPath !== location.pathname) {
                        navigate(newPath);
                    }
                },
            },
            {
                key: 'closeOthers',
                label: '关闭其他标签页',
                icon: <MinusCircleOutlined />,
                onClick: () => {
                    closeOtherTabs(tab.key);
                    if (tab.path !== location.pathname) {
                        navigate(tab.path);
                    }
                },
            },
            {
                key: 'closeAll',
                label: '关闭所有标签页',
                icon: <CloseCircleOutlined />,
                onClick: () => {
                    closeAllTabs();
                    onNavigate({ key: '/dashboard' });
                },
            },
        ],
    });

    // 操作按钮菜单
    const operationMenu = {
        items: [
            {
                key: 'closeAll',
                label: '关闭所有标签页',
                icon: <CloseCircleOutlined />,
                onClick: () => {
                    closeAllTabs();
                    onNavigate({ key: '/dashboard' });
                },
            },
            {
                key: 'closeOthers',
                label: '关闭其他标签页',
                icon: <MinusCircleOutlined />,
                onClick: () => {
                    closeOtherTabs(activeTab);
                },
            },
            {
                type: 'divider',
            },
            {
                key: 'refresh',
                label: '刷新当前页面',
                icon: <ReloadOutlined />,
                onClick: () => window.location.reload(),
            },
        ],
    };

    // 简单可靠的拖拽处理
    const handleDragStart = (e, index) => {
        setDragIndex(index);
        setIsDragging(true);
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/plain', index.toString());

        // 强制禁用文字选择
        document.body.style.userSelect = 'none';
        document.body.style.webkitUserSelect = 'none';
        document.body.style.mozUserSelect = 'none';
        document.body.style.msUserSelect = 'none';
        document.body.style.webkitTouchCallout = 'none';

        // 清除任何现有选择，但不阻止拖拽事件
        window.getSelection().removeAllRanges();
    };

    const handleDragOver = (e) => {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';
    };

    const handleDragEnter = (e, index) => {
        e.preventDefault();
        if (dragIndex !== null && index !== dragIndex) {
            setDragOverIndex(index);
        }
    };

    const handleDragLeave = (e) => {
        e.preventDefault();
    };

    const handleDrop = (e, dropIndex) => {
        e.preventDefault();
        if (dragIndex === null || dragIndex === dropIndex) {
            resetDragState();
            return;
        }

        const newTabs = [...tabs];
        const draggedTab = newTabs[dragIndex];

        // 移除被拖拽的tab
        newTabs.splice(dragIndex, 1);

        // 在新位置插入
        newTabs.splice(dropIndex, 0, draggedTab);

        reorderTabs(newTabs);
        resetDragState();
    };

    const handleDragEnd = () => {
        resetDragState();
    };

    const resetDragState = () => {
        setDragIndex(null);
        setDragOverIndex(null);
        setIsDragging(false);

        // 完全恢复页面选择
        document.body.style.userSelect = '';
        document.body.style.webkitUserSelect = '';
        document.body.style.mozUserSelect = '';
        document.body.style.msUserSelect = '';
        document.body.style.webkitTouchCallout = '';

        // 清除任何选择
        if (window.getSelection) {
            window.getSelection().removeAllRanges();
        }
    };

    // 渲染标签页内容
    const renderTabContent = (tab, index) => {
        const isActive = tab.key === activeTab;
        const isDraggedItem = dragIndex === index;
        const isDragOver = dragOverIndex === index;

        // 计算动态样式类名
        let dynamicClassName = `tab-item ${isActive ? 'active' : ''}`;
        if (isDraggedItem) {
            dynamicClassName += ' dragging';
        }

        return (
            <Dropdown
                menu={getContextMenu(tab)}
                trigger={['contextMenu']}
                key={tab.key}
            >
                <div
                    className={dynamicClassName}
                    draggable="true"
                    onDragStart={(e) => handleDragStart(e, index)}
                    onDragOver={handleDragOver}
                    onDragEnter={(e) => handleDragEnter(e, index)}
                    onDragLeave={handleDragLeave}
                    onDrop={(e) => handleDrop(e, index)}
                    onDragEnd={handleDragEnd}
                    onClick={(e) => {
                        if (!isDragging) {
                            handleTabClick(tab.key);
                        }
                    }}
                    onMouseDown={(e) => {
                        // 只清除选择，不阻止拖拽
                        if (window.getSelection) {
                            window.getSelection().removeAllRanges();
                        }
                    }}
                    style={{
                        display: 'flex',
                        alignItems: 'center',
                        padding: '8px 12px',
                        margin: '4px 2px',
                        borderRadius: 6,
                        cursor: isDraggedItem ? 'grabbing' : 'pointer',
                        backgroundColor: isActive ? token.colorPrimaryBg : 'transparent',
                        border: isActive ? `1px solid ${token.colorPrimary}` : '1px solid transparent',
                        boxShadow: isActive
                            ? `0 0 0 1px ${token.colorPrimary}`
                            : `0 0 0 1px ${token.colorBorder}20`,
                        transition: 'all 0.2s ease',
                        position: 'relative',
                        maxWidth: 200,
                        minWidth: 80,
                        opacity: isDraggedItem ? 0.7 : 1,
                        zIndex: isDraggedItem ? 1000 : 1,
                        userSelect: 'none',
                        WebkitUserSelect: 'none',
                        MozUserSelect: 'none',
                        msUserSelect: 'none',
                    }}
                    onMouseEnter={(e) => {
                        if (!isActive) {
                            e.target.style.backgroundColor = token.colorFillTertiary;
                            e.target.style.boxShadow = `0 0 0 1px ${token.colorBorder}40`;
                        }
                    }}
                    onMouseLeave={(e) => {
                        if (!isActive) {
                            e.target.style.backgroundColor = 'transparent';
                            e.target.style.boxShadow = `0 0 0 1px ${token.colorBorder}20`;
                        }
                    }}
                >
                    {/* 标签页图标 */}
                    <span
                        className="tab-icon"
                        style={{
                            fontSize: 14,
                            marginRight: 6,
                            color: isDark ? '#ffffff' : token.colorText
                        }}
                    >
                        {getIcon(tab.icon)}
                    </span>

                    {/* 标签页标题 */}
                    <Text
                        className="tab-title"
                        style={{
                            color: isActive ? token.colorPrimary : token.colorText,
                            fontWeight: isActive ? 500 : 400,
                            userSelect: 'none',
                            WebkitUserSelect: 'none',
                            MozUserSelect: 'none',
                            msUserSelect: 'none',
                        }}
                    >
                        {getTabTitle(tab)}
                    </Text>

                    {/* 关闭按钮 */}
                    {tab.closable && (
                        <Tooltip title="关闭标签页">
                            <Button
                                type="text"
                                size="small"
                                icon={<CloseOutlined />}
                                onClick={(e) => handleTabClose(e, tab.key)}
                                className="tab-close-btn"
                                style={{
                                    width: 20,
                                    height: 20,
                                    minWidth: 20,
                                    padding: 0,
                                    fontSize: 10,
                                    color: token.colorTextTertiary,
                                }}
                            />
                        </Tooltip>
                    )}
                </div>
            </Dropdown>
        );
    };

    if (tabs.length <= 1) {
        return null; // 只有一个标签页时不显示标签栏
    }

    return (
        <div
            ref={tabBarRef}
            className={`tab-bar-container ${isDark ? 'dark-theme' : ''}`}
            style={{
                display: 'flex',
                alignItems: 'center',
                padding: '8px 16px',
                height: 48,
                backgroundColor: token.colorBgContainer,
                borderBottom: `1px solid ${token.colorBorderSecondary}`,
                boxShadow: '0 1px 4px rgba(0,0,0,0.08)',
                zIndex: 5, // 降低TabBar的z-index
                position: 'relative',
                boxSizing: 'border-box',
                flexShrink: 0,
            }}
        >
            {/* 标签页列表 */}
            <div
                style={{
                    display: 'flex',
                    alignItems: 'center',
                    flex: 1,
                    overflow: 'hidden',
                }}
            >
                <div
                    style={{
                        display: 'flex',
                        alignItems: 'center',
                        overflowX: 'auto',
                        scrollbarWidth: 'none',
                        msOverflowStyle: 'none',
                    }}
                    className="tab-scroll-container"
                >
                    {tabs.map((tab, index) => renderTabContent(tab, index))}
                </div>
            </div>

            {/* 操作按钮区 */}
            <div className="tab-operations">
                <Dropdown menu={operationMenu} placement="bottomRight">
                    <Button
                        type="text"
                        icon={<MoreOutlined />}
                        size="small"
                        className="tab-operation-btn"
                        style={{
                            color: token.colorTextTertiary,
                            border: 'none',
                        }}
                    />
                </Dropdown>
            </div>

        </div>
    );
};

export default TabBar;
